package com.lk;

import java.util.HashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 闭锁：CountDownLatch
 * 当前线程只有等其他线程执行后，才会执行
 */
public class TestCountDownLatch {
    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(5);
        LatchDemo latchDemo = new LatchDemo(countDownLatch);

        long start = System.currentTimeMillis();

        for(int i = 0; i<5; i++){
            new Thread(latchDemo).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        System.out.println("执行时间："+(end - start));

    }
}

class LatchDemo implements Runnable{

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        synchronized (this){
            try {
                for(int i=0;i<100000;i++){
                    System.out.println(i);
                }
            }finally {
                latch.countDown();
            }
        }
    }
}
